package cn.wwcyc.controller;

import cn.wwcyc.domain.Menu;
import cn.wwcyc.domain.R;
import cn.wwcyc.domain.TjDw;
import cn.wwcyc.exception.WWExceptionEnum;
import cn.wwcyc.mapper.TjDwMapper;
import cn.wwcyc.service.TjDwService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dw")
public class DWController {
    @Autowired
    TjDwService tjDwService;
    @Autowired
    TjDwMapper tjDwMapper;

    //获取所有单位树
    @GetMapping("/getAll")
    public R<List<TjDw>> getAll(){

        LambdaQueryWrapper<TjDw> qw = new LambdaQueryWrapper();
        qw.isNull(TjDw::getPid);
//        qw.orderByAsc(TjDw::getXh);
        List<TjDw> list = tjDwMapper.selectList(qw);
        for(TjDw tjDw : list){
            addChildren(tjDw);
        }
        return R.success(list);
//        return null;
    }

    @GetMapping("/getPathByid")
    public R<List<Long>> getPathByid(Long id){
        List<Long> list = tjDwService.getPathByid(id);

        return R.success(list);

    }

    //获取dwid的单位树
    public R<TjDw> getDwTreeById(Long dwid){
        TjDw root = tjDwService.getDwTreeById(dwid);
        return R.success(root);
    }

    private void addChildren(TjDw tjDw) {
        LambdaQueryWrapper<TjDw> qw1 = new LambdaQueryWrapper();
        qw1.eq(TjDw::getPid, tjDw.getId());
//        qw1.orderByAsc(Menu::getXh);
        List<TjDw> tjDwList = tjDwMapper.selectList(qw1);
        if(tjDwList == null || tjDwList.size() == 0){
            return;
        }else{
            tjDw.setChildren(tjDwList);
            for(TjDw tjDw1 : tjDwList){
                addChildren(tjDw1);
            }
        }
    }


    @PostMapping
    public R save(@RequestBody TjDw dw){
        Integer i = tjDwMapper.insert(dw);
        return R.success(i);
    }

    @PostMapping("edit")
    public R edit(@RequestBody TjDw dw){
        Integer i = tjDwMapper.updateById(dw);
        return R.success(i);
    }

    @DeleteMapping
    public R<Integer> delete(@RequestParam Long id){
        try{
            Integer i = tjDwMapper.deleteById(id);
            return R.success(i);
        }catch (Exception e){
            return R.error(WWExceptionEnum.SYSTEM_ERROR);
        }
    }



    public static void main(String[] args) {

    }
}
